import "./reset.css";
import editForm from "../form/index.vue";
import fastForm from "../form/fastForm.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types.ts";
import type { FormItemProps1 } from "./fastTypes.ts";
import { getKeyList } from "@pureadmin/utils";
import { computed, h, onMounted, reactive, ref, type Ref, toRaw } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { useUserStoreHook } from "@/store/modules/user";
import { useRouter } from "vue-router";
export function useLesseesHooks() {
  return {
    treeProps: {
      children: "children",
      label: "label"
    },
    switchStyle: ref({
      width: "58px",
      height: "30px"
    })
  };
}
export function useLessees(tableRef: Ref) {
  // 添加路由实例初始化
  const router = useRouter();
  const form = reactive({
    dealerId: "",
    searchTerm: ""
  });
  const dealerName = ref("");
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    /* {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    }, */
    {
      label: "名称",
      prop: "Name",
      minWidth: 130,
      cellRenderer: ({ row }) => (
        <span
          class="name-link-style"
          onClick={() => {
            router.push({
              path: "/mytBase/lessees/detail",
              query: {
                Id: row.Id,
                Name: row.Name
              }
            });
          }}
        >
          {row.Name}
        </span>
      )
    },
    {
      label: "编码",
      prop: "Code",
      minWidth: 130
    },
    {
      label: "用户限制/数量",
      prop: "UserLimitCount",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        const [limit, count] = (row.UserLimitCount || "0/0").split("/");
        return (
          <span>
            <span style={{ color: "#409EFF" }}>{limit}</span>
            <span style={{ fontWeight: "bold" }}>/</span>
            <span style={{ color: "#67C23A" }}>{count}</span>
          </span>
        );
      }
    },
    {
      label: "频道限制/数量",
      prop: "ChannelLimitCount",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        const [limit, count] = (row.ChannelLimitCount || "0/0").split("/");
        return (
          <span>
            <span style={{ color: "#409EFF" }}>{limit}</span>
            <span style={{ fontWeight: "bold" }}>/</span>
            <span style={{ color: "#67C23A" }}>{count}</span>
          </span>
        );
      }
    },
    {
      label: "设备限制/数量",
      prop: "DeviceLimitCount",
      minWidth: 120,
      cellRenderer: ({ row }) => {
        const [limit, count] = (row.DeviceLimitCount || "0/0").split("/");
        return (
          <span>
            <span style={{ color: "#409EFF" }}>{limit}</span>
            <span style={{ fontWeight: "bold" }}>/</span>
            <span style={{ color: "#67C23A" }}>{count}</span>
          </span>
        );
      }
    },
    {
      label: "级别",
      prop: "Level",
      minWidth: 90
    },
    {
      label: "联系人",
      prop: "Contact",
      minWidth: 90
    },
    {
      label: "电话",
      prop: "Tel",
      minWidth: 90
    },
    {
      label: "地址",
      prop: "Address",
      minWidth: 90
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  //获取经销商详情
  function getDealerDetail() {
    const dealerId = useUserStoreHook()?.userId ?? 0;
    http
      .get(changeHttpLink(`/api/Dealer/${dealerId}`), {
        params: {
          dealerId: useUserStoreHook()?.userId ?? 0
        }
      })
      .then((res: any) => {
        if (res.Success) {
          form.dealerId = res.Data.Id;
          dealerName.value = res.Data.Name;
          //
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }
  //获取、搜索租户列表
  function onSearch() {
    const searchLimit = toRaw(form);
    const paginationInfo = toRaw(pagination);
    loading.value = true;
    const params: any = {
      pageIndex: paginationInfo.currentPage,
      pageSize: paginationInfo.pageSize,
      searchTerm: searchLimit.searchTerm ?? "",
      dealerId: useUserStoreHook()?.userId ?? 0
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/Tenant"), { params })
      .then((res: any) => {
        loading.value = false;
        //console.log(res);
        if (res.Success) {
          // 处理数据，添加合并字段
          const processedItems = res.Data.Items.map(item => ({
            ...item,
            UserLimitCount: `${item.UserLimit || 0}/${item.UserCount || 0}`,
            ChannelLimitCount: `${item.ChannelLimit || 0}/${item.ChannelCount || 0}`,
            DeviceLimitCount: `${item.DeviceLimit || 0}/${item.DeviceCount || 0}`
          }));
          dataList.value = processedItems;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //租户新增、修改
  function openDialog(title, row: any) {
    console.log(title);
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}租户`,
      props: {
        formInline: {
          Id: row?.Id ?? 0,
          Name: row?.Name ?? "",
          Logo: row?.Logo ?? "",
          Address: row?.Address ?? "",
          Contact: row?.Contact ?? "",
          Tel: row?.Tel ?? "",
          UserCount: row?.UserCount ?? 0,
          UserLimit: row?.UserLimit ?? 0,
          ChannelCount: row?.ChannelCount ?? 0,
          ChannelLimit: row?.ChannelLimit ?? 0,
          DeviceLimit: row?.DeviceLimit ?? 0,
          DeviceCount: row?.DeviceCount ?? 0,
          ChannelDefEnable: row?.ChannelDefEnable ?? 0,
          Utc: row?.Utc ?? 0,
          Comment: row?.Comment ?? ""
        },
        title: title // 传递title属性给表单组件
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, { ref: formRef, formInline: null, title }),
      beforeSure: (done, { options }) => {
        console.log("执行", title);
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了租户名称为【${curData.Name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新租户列表数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              id: 0,
              Name: curData.Name,
              Logo: curData.Logo,
              Address: curData.Address,
              Contact: curData.Contact,
              Tel: curData.Tel,
              UserCount: curData.UserCount ?? 0,
              UserLimit: curData.UserLimit ?? 0,
              ChannelCount: curData.ChannelCount ?? 0,
              ChannelLimit: curData.ChannelLimit ?? 0,
              DeviceLimit: curData.DeviceLimit ?? 0,
              DeviceCount: curData.DeviceCount ?? 0,
              ChannelDefEnable: curData.ChannelDefEnable ?? 0,
              Utc: curData.Utc,
              Comment: curData.Comment
              //测试
              /* Code: "Test-Tenant-1",
              I18n: "Test I18n",
              DealerName: "测试经销商1" */
            };
            console.log("表单数据", formData);
            if (title == "创建") {
              http
                .post(changeHttpLink("/api/Tenant"), {
                  data: formData
                })
                .then((res: any) => {
                  console.log(res);
                  if (res.Success) {
                    console.log("新增成功");
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                  console.error(err);
                });
            } else if (title !== "创建") {
              formData.id = id;
              // 使用标准化的request方法发送PUT请求
              http
                .request("put", changeHttpLink(`/api/Tenant/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  console.log("res", res);
                  if (res.Success) {
                    console.log("修改成功");
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  console.log("修改");
                  loading.value = false;
                  // 更详细的错误处理
                  if (err.response) {
                    // 服务器返回了错误状态码
                    message(
                      `请求失败: ${err.response.status} ${err.response.statusText}`,
                      { type: "error" }
                    );
                  } else if (err.request) {
                    // 请求已发送但未收到响应
                    message("请求超时或服务器未响应", { type: "error" });
                  } else {
                    // 设置请求时发生错误
                    message(`请求错误: ${err.message}`, { type: "error" });
                    console.error(err);
                  }
                });
            }
          }
        });
      }
    });
  }
  //快捷创建租户
  function openFastDialog(title, row: any) {
    console.log(title);
    addDialog({
      title: `快捷${title}租户`,
      props: {
        formInline: {
          Id: row?.Id ?? 0,
          Name: row?.Name ?? "",
          Contact: row?.Contact ?? "",
          Tel: row?.Tel ?? "",
          ChannelCount: row?.ChannelCount ?? ""
          //Code1: row?.Code1 ?? ""
        },
        title: title // 传递title属性给表单组件
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(fastForm, { ref: formRef, formInline: null, title }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps1;
        function chores() {
          message(`您${title}了租户名称为【${curData.Name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新租户列表数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              dealerId: useUserStoreHook()?.userId ?? 0,
              dealerName: dealerName.value,
              name: curData.Name,
              contact: curData.Contact,
              tel: curData.Tel,
              channelCount: curData.ChannelCount,
              users: (curData.Users || []).map(user => ({
                code1: user.Code1,
                name: user.Name
              }))
            };
            console.log("表单数据", formData);
            if (title == "创建") {
              http
                .post(changeHttpLink("/api/Tenant/quick-create"), {
                  data: formData
                })
                .then((res: any) => {
                  console.log(res);
                  if (res.Success) {
                    console.log("新增成功");
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                  console.error(err);
                });
            }
          }
        });
      }
    });
  }
  //删除
  function handleDelete(row) {
    http
      .request("delete", changeHttpLink(`/api/Tenant/${row.Id}`), {
        data: row.Id
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(`您删除了租户名称为${row.Name}的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  /** 批量删除 */
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const params = {
      ids: curSelected.map(item => {
        return item.Id;
      })
    };
    console.log(params);
    http
      .request("post", changeHttpLink("/api/Tenant/batch-delete"), {
        data: params
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(
            `您删除了ID为【 ${getKeyList(curSelected, "Id")}】的${curSelected.length}条数据`,
            {
              type: "success"
            }
          );
          tableRef.value.getTableRef().clearSelection();
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  //分页变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth < 1024;
  }
  onMounted(() => {
    onSearch();
    getDealerDetail();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    openFastDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    getDealerDetail
  };
}
